package com.fastloan.safe.mgt.root.service.impl;

import com.fastloan.safe.core.util.ManagerKit;
import com.fastloan.safe.mgt.auth.model.CmuRoleFun;
import com.fastloan.safe.mgt.auth.service.CmuRoleFunService;
import com.fastloan.safe.mgt.root.dao.CmFunMapper;
import com.fastloan.safe.mgt.root.model.CmuFun;
import com.fastloan.safe.mgt.root.model.vo.DefFunTreeVo;
import com.fastloan.safe.mgt.root.service.CmDefFunService;
import com.fastloan.safe.mgt.root.service.CmFunService;
import com.kawins.base.BaseMapper;
import com.kawins.base.baseabs.BaseServiceImpl;
import com.kawins.supers.tree.Bean2TreeUtil;
import com.kawins.util.colle.ListSortUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

@Service
public class CmFunServiceImpl extends BaseServiceImpl<CmuFun> implements CmFunService {

    @Autowired
    private CmFunMapper funMapper;

    @Autowired
    private CmDefFunService defFunService;

    @Autowired
    private CmuRoleFunService roleFunService;

    @Override
    protected BaseMapper<CmuFun> buildDao() {
        return funMapper;
    }

    @Override
    public void insertList(List<CmuFun> cmuFun) {
        funMapper.insertList(cmuFun);
    }

    @Override
    public List<DefFunTreeVo> selectFunTreeByOrg() {
        List<DefFunTreeVo> list = selectFunByOrg();
        return buildTree(list);
    }

    private List<DefFunTreeVo> buildTree(List<DefFunTreeVo> list) {
        LinkedHashMap<String, Integer> orderMap = new LinkedHashMap<>();
        orderMap.put("shorts", ListSortUtil.ASC);
        Bean2TreeUtil<DefFunTreeVo> bean2TreeUtil = new Bean2TreeUtil<>(orderMap);
        return bean2TreeUtil.getChildNodesByParentId(list, CmDefFunService.TOP_FUN_PARENT_ID);
    }


    @Override
    public List<DefFunTreeVo> selectFunTreeByOrgCheck(String cmuRoleId) {
        List<DefFunTreeVo> list = selectFunByOrg();
        List<CmuRoleFun> cmuRoleFuns = roleFunService.select(new CmuRoleFun().setRoleId(cmuRoleId));
        for (DefFunTreeVo defFunTreeVo : list) {
            for (CmuRoleFun cmuRoleFun : cmuRoleFuns) {
                if (cmuRoleFun.getDefFunId().equals(defFunTreeVo.getId())) {
                    defFunTreeVo.setCheck(true);
                }
            }
        }
        return buildTree(list);
    }

    @Override
    public List<DefFunTreeVo> selectFunByOrg() {
        List<CmuFun> cmuFuns = select(new CmuFun().setTopOrgId(ManagerKit.getTopOrgId()));
        List<DefFunTreeVo> list = new ArrayList<>(0);
        for (CmuFun cmuFun : cmuFuns) {
            list.addAll(defFunService.selectAllSonByTop(cmuFun.getDefFunId(), true));
        }
        return list;
    }
}
